const Router = require('koa-router');
const router = new Router();
const tools = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 库存明细
router.post('/stock/kcmx', async ctx => {
    let formData = ctx.request.body.formData;
    let excel = ctx.request.body.excel
    let beg = formData.beginDate?formData.beginDate:'1970-01-01'
    let end = formData.endDate?formData.endDate:tools.getDay()
    let tenantId = ctx.user.tenantId
    if(!formData.locationId) return ctx.err('请选择仓库')
    if(!formData.invId) return ctx.err('请选择商品')
    let locationId = formData.locationId
    let invId = formData.invId
    let sql = `
        select a.isInit,a.billDate,g.name invName,a.transTypeName,a.transType,c.name buName,round(inCount/g.spec,2) inC,round(inPrice*g.spec,2) inP,inMoney inM,a.unit,
               round(outCount/g.spec,2)  outC,
               round(costPrice*g.spec,2)  outP,
               costMoney outM,
               round(lastCount/g.spec,2) lastC,
               round(lastPrice*g.spec,2) lastP,
               lastMoney lastM,b.billNo,a.unit1 from 
        (
           SELECT  *,0 isInit from inventory_detail where tenantId = ${tenantId} and locationId=${locationId} and invId=${invId} and billDate >= '${beg}' and billDate<='${end}'
           union all
           SELECT top 1 *,1 isInit from inventory_detail where tenantId = ${tenantId} and locationId=${locationId} and invId=${invId} and billDate < '${beg}' ORDER BY seq desc
        ) a 
            inner join goods g on a.tenantId=g.tenantId and a.invId=g.id 
        left join invoice b on a.iid=b.id left join contact c on b.buId=c.id 
    `
    sql += ' order by a.seq asc '
    let list = await db.query(sql, {type: QueryTypes.SELECT})
    list.map(row => {
        if(row.isInit === 1) {
            row.billNo = ''
            row.transTypeName = '期初'
            row.billDate = ''
            row.inC = ''
            row.inP = ''
            row.inM = ''
            row.outC = ''
            row.outP = ''
            row.outM = ''
        }
    })
    if(excel) {
        return tools.doExcelOut(ctx, list)
    }
    return ctx.suc('', {
        total: 0,
        list
    })
})


module.exports = router;
